package com.example.aaa_viewpager.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.example.aaa_viewpager.entity.UserCustom;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View.OnCreateContextMenuListener;

/**
 * 
 */
public class UserCustomDao {
	private static final String DB_NAME = "custom.db";
	private static final String TAG = "SQLITE";
	private Context ctx;

	public UserCustomDao(Context ctx) {
		super();
		this.ctx = ctx;
	}

	// Open Database
	private void copyDatabase(File dbFile) throws IOException {
		InputStream is = ctx.getAssets().open(DB_NAME);
		OutputStream os = new FileOutputStream(dbFile);

		byte[] buffer = new byte[1024];
		while (is.read(buffer) > 0) {
			os.write(buffer);
		}

		os.flush();
		os.close();
		is.close();
	}

	public SQLiteDatabase openReadDatabase() {
		File dbFile = ctx.getDatabasePath(DB_NAME);

		if (!dbFile.exists()) {
			try {
				File parentDir = new File(dbFile.getParent());
				if (!parentDir.exists()) {
					parentDir.mkdir();
				}
				copyDatabase(dbFile);
			} catch (IOException e) {
				throw new RuntimeException("Error creating source database", e);
			}
		}

		return SQLiteDatabase.openDatabase(dbFile.getPath(), null,
				SQLiteDatabase.OPEN_READONLY);
	}

	public SQLiteDatabase openWriteDatabase() {
		File dbFile = ctx.getDatabasePath(DB_NAME);

		if (!dbFile.exists()) {
			try {
				File parentDir = new File(dbFile.getParent());
				if (!parentDir.exists()) {
					parentDir.mkdir();
				}
				copyDatabase(dbFile);
			} catch (IOException e) {
				throw new RuntimeException("Error creating source database", e);
			}
		}

		return SQLiteDatabase.openDatabase(dbFile.getPath(), null,
				SQLiteDatabase.OPEN_READWRITE);
	}

//	// CRUD
//	public List<UserCustom> getAll() {
//		List<UserCustom> ret = new ArrayList<UserCustom>();
//		SQLiteDatabase db = this.openReadDatabase();
//		String sql = "SELECT * FROM CUSTOM;";
//		Cursor cursor = db.rawQuery(sql, null);
//		if (cursor.moveToFirst()) {
//			do {
//				int id = cursor.getInt(0);
//				String name = cursor.getString(1);
//				String address = cursor.getString(2);
//				byte[] picture = cursor.getBlob(3);
//				String notes = cursor.getString(4);
//				UserCustom u = new UserCustom(id, name, notes);
//				ret.add(u);
//			} while (cursor.moveToNext());
//		}
//		return ret;
//	}

	public ArrayList<HashMap> getAll() {
		ArrayList<HashMap> ret = new ArrayList<HashMap>();
		SQLiteDatabase db = this.openReadDatabase();
		String sql = "SELECT * FROM CUSTOM;";
		Cursor cursor = db.rawQuery(sql, null);
		HashMap item = null;
		if (cursor.moveToFirst()) {
			do {
				int id = cursor.getInt(0);
				String name = cursor.getString(1);
				String address = cursor.getString(2);
				byte[] picture = cursor.getBlob(3);
				item = new HashMap();
				item.put("name", name);
				item.put("address", address);
				item.put("picture", picture);
				ret.add(item);
			} while (cursor.moveToNext());
		}
		cursor.close();
		db.close();
		return ret;
	}
	
	//bb_details 使用者清單 新增項目使用
	public boolean getUserById(String name) {
		SQLiteDatabase db = this.openReadDatabase();
		String sql = "SELECT * FROM CUSTOM WHERE NAME = " + "'" + name + "'"
				+ ";";
		// String sql = "SELECT * FROM CUSTOM";
		Cursor cursor = db.rawQuery(sql, null);

		boolean flag = false;
		// 如果資料庫內沒有'name'的值 if (cursor.moveToFirst()) 的判斷為false =>資料庫有值
		// 如果資料庫內有'name'的值 if (cursor.moveToFirst()) 的判斷為true =>資料庫沒有值
		if (cursor.moveToFirst()) {
			flag = false;

		} else {
			flag = true;
		}
		return flag;
	}
	//在BB_notes使用...取得pic
	public UserCustom getPicByName(String name) {
		SQLiteDatabase db = this.openReadDatabase();
		String sql = "SELECT * FROM CUSTOM WHERE NAME = " + "'" + name + "'"+ ";";
		Cursor cursor = db.rawQuery(sql, null);
		UserCustom ret = null;
		if (cursor.moveToFirst())
		{
			byte[] picture = cursor.getBlob(3);
			ret = new UserCustom(picture);
		}
		return ret;
	}
	//在BB_notes使用...取得notes	
	public UserCustom getNotesByName(String name) {
		SQLiteDatabase db = this.openReadDatabase();
		String sql = "SELECT * FROM CUSTOM WHERE NAME = " + "'" + name + "'"+ ";";
		Cursor cursor = db.rawQuery(sql, null);
		UserCustom ret = null;
		if (cursor.moveToFirst())
		{
			String notes = cursor.getString(4);
			ret = new UserCustom(notes);
		}
		return ret;
	}
	//在BB_notes使用...取得address	
		public UserCustom getAddressByName(String name) {
			SQLiteDatabase db = this.openReadDatabase();
			String sql = "SELECT * FROM CUSTOM WHERE NAME = " + "'" + name + "'"+ ";";
			Cursor cursor = db.rawQuery(sql, null);
			UserCustom ret = null;
			if (cursor.moveToFirst())
			{
				String address = cursor.getString(2);
				ret = new UserCustom(address);
			}
			return ret;
		}

	public UserCustom getUserById(int position) {
		SQLiteDatabase db = this.openReadDatabase();
		// String sql = "SELECT * FROM CUSTOM WHERE ID = " + "'" + id + "'" +
		// ";";
		String sql = "SELECT * FROM CUSTOM";
		Cursor cursor = db.rawQuery(sql, null);
		UserCustom ret = null;
		if (cursor.moveToFirst()) {
			cursor.moveToPosition(position);
			int id = cursor.getInt(0);
			String name = cursor.getString(1);
			String address = cursor.getString(2);
			byte[] picture = cursor.getBlob(3);
			ret = new UserCustom(id, name, address,picture);
		}
		return ret;
	}

	public boolean insert(UserCustom u) {
		SQLiteDatabase db = this.openWriteDatabase();
		try {
			long uid = db.insert("CUSTOM", null, u.toContentValues());
			Log.i(TAG, "New ID = " + uid);

		} catch (Exception ex) {

			Log.e(TAG, ex.getMessage());
			return false;
		}
		db.close();
		return true;
	}

	public boolean delete(int id) {
		SQLiteDatabase db = this.openWriteDatabase();
		try {
			db.delete("CUSTOM", "_id=?", new String[] { id + "" });
		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage());
			return false;
		}
		db.close();
		
		return true;
	}

	//BB_notes使用 對應民宿名稱...更新Notes欄位
	public boolean update(String str, String name) {
		SQLiteDatabase db = this.openWriteDatabase();
		
		String sql = "UPDATE CUSTOM SET NOTES = " + "'" + str + "'"
				+ " WHERE NAME = " + "'" + name + "'" + ";";
		
		Cursor cursor = db.rawQuery(sql, null);
		cursor.moveToFirst();
		ContentValues values = new ContentValues();

		values.put("NOTES", str);

		db.close();
		return true;
	}

	// cursor simpleCusorAdapter使用
	public Cursor getAllNotesCursor() {

		String selectQuery = "SELECT * FROM CUSTOM;";
		SQLiteDatabase db = this.openReadDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);
		return cursor;
	}
	
	  
}
